
package com.av.torrent.jobs;

import com.av.torrent.jobs.manager.subscriber.Subscriber;

import android.os.AsyncTask;
import android.util.Log;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Uladzimir_Kerus
 * @param <T>
 */
public abstract class AbstractSubscribableJob<T> extends AsyncTask<Void, Void, T> implements Job<T> {

  private static final String LOG_TAG = AbstractSubscribableJob.class.getSimpleName();

  private final List<Subscriber<T>> mSubscribers = new LinkedList<Subscriber<T>>();

  private Exception mExecutionException = null;

  public void addSubscriber(final Subscriber<T> subscriber) {
    mSubscribers.add(subscriber);
  }

  public void removeSubscriber(final Subscriber<T> subscriber) {
    mSubscribers.remove(subscriber);
  }

  /*
   * (non-Javadoc)
   * @see android.os.AsyncTask#doInBackground(Params[])
   */
  @Override
  protected T doInBackground(Void... params) {
    Log.d(LOG_TAG, String.format("In doInBackground(Void...): is about to execute the job = %s", String.valueOf(this)));
    try {
      return process();
    } catch (Exception ex) {
      final String errorMessage = ex.getLocalizedMessage();
      Log.e(LOG_TAG,
          String.format("In doInBackground(Void...): error occurred while executing the job: %s", errorMessage));
      mExecutionException = ex;
      return null;
    } finally {
      Log.d(LOG_TAG,
          String.format("In doInBackground(Void...): execution of the job finished [job = %s]", String.valueOf(this)));
    }
  }

  /*
   * (non-Javadoc)
   * @see android.os.AsyncTask#onPreExecute()
   */
  @Override
  protected void onPreExecute() {
    Log.d(LOG_TAG, String.format("In onPreExecute(): number of subscribers is %d", mSubscribers.size()));
    if (!mSubscribers.isEmpty()) {
      for (Subscriber<T> subscriber : mSubscribers) {
        subscriber.onPreExecute();
      }
    }
  }

  /*
   * (non-Javadoc)
   * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
   */
  @Override
  protected void onPostExecute(T result) {
    Log.d(LOG_TAG, String.format("In onPostExecute(T): number of subscribers is %d", mSubscribers.size()));
    if (!mSubscribers.isEmpty()) {
      if (mExecutionException != null) {
        for (Subscriber<T> subscriber : mSubscribers) {
          subscriber.onError(mExecutionException);
        }
      } else {
        for (Subscriber<T> subscriber : mSubscribers) {
          subscriber.onFinished(result);
        }
      }
    }
  }
}
